package com.bstek.uflo.console.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.uflo.deploy.validate.ProcessValidateException;
import com.bstek.uflo.service.ProcessService;

/**
 * @author Jacky.gao
 * @since 2013年9月9日
 */
public class DeployProcessController extends AbstractController{
	private ProcessService processService;
	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest req,HttpServletResponse response) throws Exception {
		preCheck();
		InputStream inputStream=null;
		if(req instanceof MultipartRequest){
			DefaultMultipartHttpServletRequest request=(DefaultMultipartHttpServletRequest)req;
			request.setCharacterEncoding("utf-8");
			MultipartFile file=request.getFile("processFile");
			inputStream=file.getInputStream();
		}else{
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletContext servletContext = req.getSession().getServletContext();
			File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
			factory.setRepository(repository);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");
			for(FileItem item:upload.parseRequest(req)){
				if(item.getFieldName().equals("processFile")){
					inputStream=item.getInputStream();
				}
			}
		}
		if(inputStream!=null){
			Map<String,Object> result=new HashMap<String,Object>();
			try{
				processService.deployProcess(inputStream);
				result.put("result", "success");
			}catch(Exception ex){
				ex.printStackTrace();
				result.put("result", "fail");
				Throwable exception= getCause(ex);
				if(exception instanceof ProcessValidateException){
					ProcessValidateException e=(ProcessValidateException)exception;
					result.put("error", e.getMessage());
				}else{
					result.put("error", ex.getMessage());					
				}
			}
			ObjectMapper mapper=new ObjectMapper();
			response.setContentType("text/json");  
			response.setCharacterEncoding("UTF-8");  
			OutputStream out=response.getOutputStream();
			try{
				mapper.writeValue(out,result);
			}finally{
				out.flush();
				out.close();
			}
		}else{
			throw new IllegalArgumentException("Can not found uflo process definition!");				
		}
		return null;
	}
	
	private Throwable getCause(Throwable ex){
		if(ex.getCause()==null){
			return ex;
		}else{
			return getCause(ex.getCause());
		}
	}
	
	public void setProcessService(ProcessService processService) {
		this.processService = processService;
	}

}
